package leetcode.editor.cn;

/**
 * @author: yangwk
 * @date: 2023/6/7
 * @description:
 **/
public class P64 {
    public static void main(String[] args) {
        System.out.println(minPathSum(new int[][]{
                {1, 3, 1},
                {1, 5, 1},
                {4, 2, 1}}));
    }

    public static int minPathSum(int[][] grid) {
        int[][] dp = new int[grid.length][grid[0].length];
        int row = grid.length, col = grid[0].length;
        int pre = 0;
        for (int i = 0; i < row; i++) {
            dp[i][0] = grid[i][0] + pre;
            pre = dp[i][0];
        }
        pre = 0;
        for (int i = 0; i < col; i++) {
            dp[0][i] = grid[0][i] + pre;
            pre = dp[0][i];
        }
        for (int i = 1; i < grid.length; i++) {
            for (int j = 1; j < grid[0].length; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[grid.length - 1][grid[0].length - 1];
    }
}
